package com.keensense.vcm.internal;

import com.keensense.vcm.HttpMethod;
import com.keensense.vcm.common.auth.CredentialsProvider;
import com.keensense.vcm.common.comm.RequestMessage;
import com.keensense.vcm.common.comm.ServiceClient;
import com.keensense.vcm.common.parser.ResponseParsers;
import com.keensense.vcm.model.*;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lanjian
 * @date 2020/8/1
 */
public class SubscriptionOperation extends VCMOperation {

    public SubscriptionOperation(ServiceClient client, CredentialsProvider credsProvider) {
        super(client, credsProvider);
    }

    /**
     * 数据订阅并获取连接
     */
    public SubscriptionResponse subscription(SubscriptionRequest subscriptionRequest) {
        String xml = getXmlFromObject(subscriptionRequest, SubscriptionRequest.class);
        InputStream in = new ByteArrayInputStream(xml.getBytes());
        RequestMessage request = new VCMRequestMessageBuilder(getInnerClient()).setInputStream(in)
                .setInputSize(xml.getBytes().length).setEndpoint(endpoint).setMethod(HttpMethod.POST).build();
        request.setResourcePath(VCMResourcePathConstants.SUBSCRIPTION);
        SubscriptionResponse result = doOperation(request, ResponseParsers.subscriptionResponseParser, true);
        return result;
    }


    /**
     * 数据订阅信息查询
     */
    public SearchSubscriptionResponse searchSubscription(SearchSubscriptionRequest searchSubscriptionRequest) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/xml");
        String xml = getXmlFromObject(searchSubscriptionRequest, SearchSubscriptionRequest.class);
        InputStream in = new ByteArrayInputStream(xml.getBytes());
        RequestMessage request = new VCMRequestMessageBuilder(getInnerClient()).setInputStream(in).setHeaders(headers)
                .setInputSize(xml.getBytes().length).setEndpoint(endpoint).setMethod(HttpMethod.POST).build();
        request.setResourcePath(VCMResourcePathConstants.SEARCH_SUBSCRIPTION);
        SearchSubscriptionResponse result = doOperation(request, ResponseParsers.searchSubscriptionResponseParser, true);
        return result;
    }

    /**
     * 取消数据订阅
     */
    public VCMResponse deleteSubscription(DeleteSubscriptionRequest deleteSubscriptionRequest) {
        String xml = getXmlFromObject(deleteSubscriptionRequest, DeleteSubscriptionRequest.class);
        InputStream in = new ByteArrayInputStream(xml.getBytes());
        RequestMessage request = new VCMRequestMessageBuilder(getInnerClient()).setMethod(HttpMethod.DELETE).setInputStream(in)
                .setInputSize(xml.getBytes().length).setEndpoint(endpoint).build();
        request.setResourcePath(VCMResourcePathConstants.SUBSCRIPTION);
        return doOperation(request, emptyResponseParser, true);
    }
}
